// 键盘布局配置
const KEYBOARD_LAYOUT = [
  ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'backspace'],
  ['tab', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\'],
  ['caps', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', 'enter'],
  ['shift', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 'shift'],
  ['ctrl', 'win', 'alt', 'space', 'alt', 'win', 'menu', 'ctrl']
];

document.addEventListener('DOMContentLoaded', function() {
  createKeyboard();
  updateStats();
  
  document.getElementById('resetStats').addEventListener('click', function() {
    if(confirm('确定要重置所有统计数据吗？')) {
      chrome.storage.local.set({ keyStats: {} }, function() {
        updateStats();
      });
    }
  });
});

function createKeyboard() {
  const container = document.getElementById('keyboardStats');
  
  KEYBOARD_LAYOUT.forEach(row => {
    const rowDiv = document.createElement('div');
    rowDiv.className = 'keyboard-row';
    
    row.forEach(key => {
      const keyDiv = document.createElement('div');
      keyDiv.className = `key ${key.toLowerCase()}`;
      keyDiv.innerHTML = `
        <span class="key-name">${key.toUpperCase()}</span>
        <span class="key-count" id="key-${key.toLowerCase()}">0</span>
      `;
      rowDiv.appendChild(keyDiv);
    });
    
    container.appendChild(rowDiv);
  });
}

function updateStats() {
  chrome.storage.local.get('keyStats', function(result) {
    const stats = result.keyStats || {};
    
    // 更新总按键次数
    const totalCount = Object.values(stats).reduce((sum, count) => sum + count, 0);
    document.getElementById('totalCount').textContent = totalCount.toLocaleString();

    // 重置所有按键计数为0
    document.querySelectorAll('.key-count').forEach(elem => {
      elem.textContent = '0';
    });

    // 更新每个按键的计数
    Object.entries(stats).forEach(([key, count]) => {
      const elem = document.getElementById(`key-${key.toLowerCase()}`);
      if (elem) {
        elem.textContent = count.toLocaleString();
      }
    });
  });
}

// 每秒更新一次统计数据
setInterval(updateStats, 1000); 